package com.common.web.exception;

import com.common.core.exception.BizException;
import com.common.core.exception.SysException;
import com.common.core.exception.code.BaseErrorCode;
import com.common.core.exception.code.WebErrorCode;
import com.common.core.results.VoidResult;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.core.annotation.Order;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;
import org.springframework.web.servlet.NoHandlerFoundException;

import javax.servlet.http.HttpServletRequest;
import java.util.Objects;

/**
 * @auther WuJun.Zhang
 * @date 2022/3/22 上午11:23
 */
@Order(value = 10)
@RestControllerAdvice
public class GlobalExceptionHandler {

    private final Logger logger = LoggerFactory.getLogger(this.getClass());

    @ExceptionHandler(value = Exception.class)
    public ResponseEntity<VoidResult> exceptionHandler(Exception e) {
        logger.error("程序服务异常,请求路径:{},异常信息:", getURL(), e);
        return ResponseEntity.status(HttpStatus.BAD_REQUEST).body(result(BaseErrorCode.ERROR));
    }

    @ExceptionHandler(value = BizException.class)
    public ResponseEntity<VoidResult> bizExceptionHandler(BizException e) {
        logger.error("业务服务异常,请求路径:{},异常信息:", getURL(), e);
        return ResponseEntity.status(HttpStatus.BAD_REQUEST).body(VoidResult.failed(Integer.parseInt(e.getErrCode()), e.getMessage()));
    }

    @ExceptionHandler(value = SysException.class)
    public ResponseEntity<VoidResult> sysExceptionHandler(SysException e) {
        logger.error("系统服务异常,请求路径:{},异常信息:", getURL(), e);
        return ResponseEntity.status(HttpStatus.BAD_REQUEST).body(VoidResult.failed(Integer.parseInt(e.getErrCode()), e.getMessage()));
    }

    @ExceptionHandler(value = NoHandlerFoundException.class)
    public ResponseEntity<VoidResult> noHandlerFoundException(NoHandlerFoundException e) {
        logger.error("请求不存在,请求路径:{},异常信息:", getURL(), e);
        return ResponseEntity.status(HttpStatus.NOT_FOUND).body(result(WebErrorCode.S_ERROR_NO_HANDLER_FOUND));
    }

    private VoidResult result(BaseErrorCode codeEnum) {
        return VoidResult.failed(codeEnum);
    }

    private String getURL() {
        HttpServletRequest request = ((ServletRequestAttributes) Objects.requireNonNull(RequestContextHolder.getRequestAttributes())).getRequest();
        return request.getServletPath();
    }
}
